﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace 数据挖掘实验
{
	public static class ImageProcessor
	{
		/// 读取图片文件
		/// </summary>
		/// <param name="path">图片文件路径</param>
		/// <returns>图片文件</returns>
		public static Bitmap ReadAsBitmap(String path)
		{
			Bitmap bitmap = null;
			using (var fileStream = File.OpenRead(path))
			{
				Int32 filelength = 0;
				filelength = (int)fileStream.Length;
				var image = new Byte[filelength];
				fileStream.Read(image, 0, filelength);
				var result = Image.FromStream(fileStream);
				fileStream.Close();
				bitmap = new Bitmap(result);
			}
			return bitmap;
		}

        public static unsafe byte[] ConvertTo8Byte(Bitmap img)
        {
            byte[] result = new byte[img.Width * img.Height];
            int n = 0;
            BitmapData data = img.LockBits(new Rectangle(0, 0, img.Width, img.Height), ImageLockMode.ReadOnly,
                                           PixelFormat.Format24bppRgb);
            var bp = (byte*)data.Scan0.ToPointer();

            for (int i = 0; i != data.Height; i++)
            {
                for (int j = 0; j != data.Width; j++)
                {
                    result[n] = bp[i * data.Stride + j * 3];
                    n++;
                    //0.3R+0.59G+0.11B 灰度计算方法
                    //float value = 0.11F * bp[i * data.Stride + j * 3] + 0.59F * bp[i * data.Stride + j * 3 + 1] +
                    //              0.3F * bp[i * data.Stride + j * 3 + 2];

                }
            }
            img.UnlockBits(data);
            return result;
        }
    }
}
